package user

import (
	"context"
	"github.com/axengine/utils/hash"
	"github.com/axengine/utils/random"
	"github.com/pkg/errors"
	"trusteva/app/rbac/model"

	"trusteva/app/rbac/internal/svc"
	"trusteva/app/rbac/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserCreateLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserCreateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserCreateLogic {
	return &UserCreateLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserCreateLogic) UserCreate(req *types.UserCreateRo) (resp *types.BaseRsp, err error) {
	if tx := l.svcCtx.DB.WithContext(l.ctx).Where("Login=?", req.Login).
		Find(&model.User{}); tx.Error != nil {
		return nil, err
	} else if tx.RowsAffected > 0 {
		return nil, errors.New("登录名已存在")
	}
	if len(req.Password) == 0 {
		return nil, errors.New("密码错误")
	}

	salt := random.RandAlphaAndDigits(8, true)
	hashedPswd := hash.Keccak256Base64([]byte(req.Password + salt))
	u := &model.User{
		Username: req.Username,
		Login:    req.Login,
		Password: hashedPswd,
		Salt:     salt,
		Memo:     req.Memo,
	}
	err = l.svcCtx.DB.WithContext(l.ctx).Create(u).Error

	return
}
